import React, { useEffect, useState } from 'react'
import {
  Button,
  Form,
  Input,
  Table,
  Modal,
  message,
  InputNumber,
  Select,
  DatePicker,
  Popconfirm
} from 'antd'
import dayjs from 'dayjs'
import { useApi } from '../../api'

//下拉框
const { Option } = Select

function ArticleType() {
  // 获取api
  const { getArticleType, changeTypeStatus, deleteType, addArticleType } = useApi()

  //分类表格信息
  const [tableData, setTableData] = useState()

  // 0新增，1编辑
  const [modalType, setModalType] = useState(0)
  const [isModalOpen, setIsModalOpen] = useState(false)

  //当前被修改或删除的行的数据
  const [currentRow, setCurrentRow] = useState(null)

  // 获取列表信息
  const getTableData = async () => {
    try {
      let res = await getArticleType()
      setTableData(res)
    } catch (error) {
      message.error('异常')
      console.log('err', error)
    }
  }

  // 获取数据
  useEffect(() => {
    getTableData()
  }, [])

  // 列表项
  const columns = [
    {
      title: '类型',
      dataIndex: 'typeName'
    },
    {
      title: '编号',
      dataIndex: 'id'
    },
    {
      title: '创建时间',
      dataIndex: 'date',
      render: val => {
        return val ? dayjs(+val).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: val => {
        return val == 1 ? '禁用' : '正常'
      }
    },
    {
      title: '操作',
      render: rowData => {
        return (
          <div className="flex">
            <Button className="mr-[0.0625rem]" onClick={() => handleClick('edit', rowData)}>
              编辑
            </Button>
            <Popconfirm
              type="提示"
              description="此操作将删除该类型，是否继续"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(rowData)}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        )
      },
      width: '5rem'
    }
  ]

  //创建form实例
  const [form] = Form.useForm()

  // 点击新增或者编辑按钮
  const handleClick = (type, rowData) => {
    setIsModalOpen(!isModalOpen)
    if (type === 'add') {
      setModalType(0)
    } else {
      setModalType(1)
      setCurrentRow(rowData)
      // 表单数据回填
      form.setFieldsValue(rowData)
    }
  }

  //点击删除按钮
  const handleDelete = async rowData => {
    try {
      let res = await deleteType({
        id: rowData.id
      })
      message.success('删除成功')
      getTableData()
    } catch (error) {
      message.error('异常')
      console.log('err', error)
    }
  }

  // 弹窗确定
  const handleOk = () => {
    //表单校验
    form.validateFields().then(
      async val => {
        try {
          //编辑
          if (modalType) {
            let params = {
              id: currentRow.id,
              status: val.status
            }
            let res = await changeTypeStatus(params)
            handleCancel()
            getTableData()
            message.success('编辑成功')
          } else {
            let res = await addArticleType(val)
            handleCancel()
            getTableData()
            message.success('添加成功')
          }
        } catch (error) {
          message.error(error)
          console.log('err', error)
        }
      },
      () => {
        message.error('异常')
      }
    )
  }
  // 弹窗取消
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  return (
    <>
      <div className="flex justify-between">
        <Button type="primary" onClick={() => handleClick('add')}>
          +新增
        </Button>
      </div>
      <Table className="mt-0.5" columns={columns} dataSource={tableData} rowKey={'id'}></Table>
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑类别' : '新增类别'}
        onCancel={handleCancel}
        cancelText="取消"
        onOk={handleOk}
        okText="确定"
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} labelAlign="left">
          {/* {modalType == 1 && (
            <Form.Item name="id">
              <Input></Input>
            </Form.Item>
          )} */}
          {modalType == 0 && (
            <Form.Item
              label="新闻类别"
              name="articleType"
              rules={[{ required: true, message: '请输入类别' }]}
            >
              <Input placeholder="请输入类别"></Input>
            </Form.Item>
          )}
          {modalType == 1 && (
            <Form.Item
              label="状态"
              name="status"
              rules={[{ required: true, message: '请输入类别' }]}
            >
              <Select initialValues={'0'}>
                <Option value="0">正常</Option>
                <Option value="1">禁用</Option>
              </Select>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  )
}

export default ArticleType
